import 'dart:io';

import 'package:device_info/device_info.dart';
import 'package:dio/dio.dart';
import 'package:flutter_app_study/utils/CommonInterceptor.dart';
import 'package:logger/logger.dart';

class DioUtil {
  static Dio dio;

  static Dio createInstance() {
    if (dio == null) {
      /// 全局属性
      var options = BaseOptions(
        connectTimeout: 15000,
        receiveTimeout: 15000,
        responseType: ResponseType.json,
        contentType: ContentType.json.toString(),
      );
      dio = new Dio(options);
      dio.interceptors.add(CommonHeaderInterceptor());
      dio.interceptors.add(ErrorInterceptor());
    }
    return dio;
  }

  static void get(String url,
      {Map<String, dynamic> data, Function success, Function error}) async {
    if (data != null && data.isNotEmpty) {
      StringBuffer options = new StringBuffer('?');
      data.forEach((key, value) {
        options.write('${key}=${value}&');
      });
      String optionsStr = options.toString();
      optionsStr = optionsStr.substring(0, optionsStr.length - 1);
      url += optionsStr;
    }
    try {
      Response response = await createInstance().get(url);
      if (success != null && response.statusCode == 200) {
        success(response.data);
      } else if (error != null) {
        error();
      }
    } catch (e) {
      print(e.toString());
      if (error != null) {
        error();
      }
    }
  }

  static void post(String url,
      {Map<String, dynamic> data, Function success, Function error}) async {
    try {
      Response response = await createInstance().post(url, data: data);
      if (success != null && response.statusCode == 200) {
        success(response.data);
      } else if (error != null) {
        error();
      }
    } catch (e) {
      print(e.toString());
      if (error != null) {
        error();
      }
    }
  }

  static Future<String> getDeviceInfo() async {
    DeviceInfoPlugin deviceInfo = DeviceInfoPlugin();
    if(Platform.isAndroid){
      AndroidDeviceInfo androidInfo = await deviceInfo.androidInfo;
      return androidInfo.model;
    }else{
      IosDeviceInfo iosInfo = await deviceInfo.iosInfo;
      return iosInfo.utsname.machine;
    }

  }

}
